package com.hw.one.transpot.entity;

import com.hw.one.collect.entity.CommonData;
import com.hw.one.collect.util.ByteUtil;
import com.hw.one.collect.util.JsonUtil;

/**
 * @Class TCPDataTransporter
 * @Author guoshenzhen
 * @Date 2018/3/14 10:38
 */
public class TCPDataTransporter implements DataTransporter<CommonData> {
	private byte[] head;
	private byte[] body;

	@Override
	public byte[] toByteArray(CommonData o) {
		init(o);
		if (null == head || null == body) {
			return null;
		}
		byte[] respData = new byte[head.length + body.length];
		System.arraycopy(head, 0, respData, 0, head.length);
		System.arraycopy(body, 0, respData, head.length, body.length);
		return respData;
	}

	@Override
	public String toJSON(CommonData o) {
		String json = JsonUtil.createTranslotarJSON(o);
		return json;
	}

	@Override
	public void init(CommonData o) {
		String json = this.toJSON(o);
		byte[] bytes = json.getBytes();
		this.setBody(bytes);
		this.setHead(ByteUtil.getBytesLength(bytes.length));
	}

	public byte[] getHead() {
		return head;
	}

	public void setHead(byte[] head) {
		this.head = head;
	}

	public byte[] getBody() {
		return body;
	}

	public void setBody(byte[] body) {
		this.body = body;
	}
}
